<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
const logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const adv = reactive({
  add: true,
  maxnum: 1,
  forFree: 1,
  setTrueStyle: {},
  imgs: [],
  option: {
    viewMode: 0,
    dragMode: 'move',
    aspectRatio: 1,
    autoCropArea: 1,
    center: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false
  },
  cropImg: proxy.$Global.cropImg
})
const form = reactive({ name: '' })

/* ---- */
const uploadoss = ref()
const layer = ref()
const layerLoading = ref()

/* ---- */
const getFormInfo = () => {
  adv.setTrueStyle = { height: `${document.querySelector('.squareBox dl dd label').clientWidth / adv.forFree}px` }
  // -- 获取信息 --
  if (proxy.$route.query.id) {
    const forTagData = { params: { 'ProCategorySearch[id]': proxy.$route.query.id } }
    proxy.$Axios.all([
      proxy.$Axios.get('pro-category/index', forTagData)
    ]).then(proxy.$Axios.spread((tagData) => {
      const TData = tagData.items[0] || {}
      if (TData.name) form.name = TData.name
      // ----
      proxy.$Myfun.getJsonData(TData.icon_json, (resJson) => {
        resJson.forEach((item) => {
          adv.imgs.push({
            imgName: item.name,
            imgUrl: item.image,
            imgW: item.width,
            imgH: item.height
          })
        })
        if (Number(adv.imgs.length) >= Number(adv.maxnum) && Number(adv.maxnum) > 0) adv.add = !adv.add
      })
    })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
}
// --上传图片操作--
const uploadAct = (type, selectObj, event, index) => {
  const uploadOss = uploadoss.value
  switch (Number(type)) {
    case 1: {
      uploadOss.uploadImg(event, selectObj,'imgs', index)
      break
    }
    case 2: {
      uploadOss.delInfo(selectObj, event)
      break
    }
  }
}
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
}
// ----
const subform = async () => {
  if (Number(form.name.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写分类名称！')
    return false
  }
  // ----
  let forImg = ''
  if (Number(adv.imgs.length) > 0) {
    const imgItems = []
    adv.imgs.forEach((item) => {
      imgItems.push({
        name: item.imgName,
        image: item.imgUrl,
        width: item.imgW,
        height: item.imgH
      })
    })
    forImg = JSON.stringify(imgItems)
  }
  // ----
  let forType = 'post'
  let forUrl = 'pro-category/create'
  let forData = {
    dealer_id: logUser.id || undefined,
    // ----
    name: form.name,
    icon_json: forImg,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  if (proxy.$route.query.id) {
    forType = 'patch'
    forUrl = 'pro-category/update?id=' + proxy.$route.query.id
    forData = {
      name: form.name,
      icon_json: forImg,
      // ----
      config_id: userInfo.config_id,
      openid: userInfo.openid
    }
  }
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  let resData = ''
  await proxy.$http[forType](forUrl, forData).then((res) => { resData = res }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  proxy.$Myfun.disLoading(layerLoading.value, 'close')
  if (resData) proxy.$router.back()
}
const goback = () => { proxy.$router.back() }

/* ---- */
onMounted(() => {
  getFormInfo()
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <div class="formSet">
      <ul>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>分类名称</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.name"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.name"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-imgs xw-radius-3 squareBox">
            <div class="FIS-top xw-flex xw-flex-align xw-flex-justify">
              <span class="FIS-title">分类图标</span>
            </div>
            <dl class="FIS-img">
              <dd v-for="(item, index) in adv.imgs"><label class="xw-block xw-act"><img :src="item.imgUrl"/><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, adv, $event, index)"/></label><span class="FIS-del fal fa-times xw-act" @click="uploadAct(2, adv, index)"></span></dd>
              <dd v-if="adv.add"><label class="xw-act xw-flex xw-flex-center" :style="adv.setTrueStyle"><em class="fal fa-plus"></em><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, adv, $event)"/></label></dd>
            </dl>
          </div>
        </li>
      </ul>
      <div class="form-sub xw-radius-3 xw-bgCL-11 xw-act" @click="subform">确定提交</div>
      <div class="form-sub xw-radius-3 xw-WhiteRed xw-act" @click="goback">取消返回</div>
    </div>
    <uploadoss-view ref="uploadoss"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>